package de.tum.in.eist.poll.server;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import de.tum.in.eist.poll.pub.service.ExtPollService;
import de.tum.in.eist.poll.pub.shared.Feedback;
import de.tum.in.eist.poll.pub.shared.Lecture;
import de.tum.in.eist.poll.pub.shared.LecturePush;
import de.tum.in.eist.poll.pub.shared.Lecturer;
import de.tum.in.eist.poll.pub.shared.Student;
import de.tum.in.eist.poll.pub.shared.User;

public class ExtPollServiceImpl extends RemoteServiceServlet implements ExtPollService {

	private static int id = 1;
	
	

	@Override
	public String addFeedback(Feedback feedback) throws Exception {
		try{
			Sql sql = new Sql("jdbc:mysql://localhost/EIST_POLL", "root", "root");
			sql.executeUpdate("INSERT INTO Feedback (lecture, opinion, like, dislike, user) VALUES " +
					"(\""+feedback.getLecture().getId()
					+"\", \""+ feedback.getOpinion()
					+"\", \""+ feedback.getLike()
					+"\", \""+ feedback.getDislike()
					+"\", \""+ feedback.getStudent().getId()+"\")");
			sql.closeConnection();
		}
		catch(Exception e){
			throw (e);
		}
		
		synchronized(PushServiceImpl.lock){
			PushServiceImpl.lecture = new LecturePush(feedback.getLecture(), feedback.getStudent(), id++);
			PushServiceImpl.lock.notifyAll();
		}
		return "Submitted";
	}



	@Override
	public List<User> getUsers() {
		// TODO Auto-generated method stub
		return null;
	}



	@Override
	public User login(String name, String password) throws IllegalArgumentException{
		try {
			Sql sql = new Sql("jdbc:mysql://localhost/EIST_POLL", "root", "root");
			ResultSet res = sql.executeQuerry("SELECT * FROM Users WHERE name = \""+name+"\" AND password = \""+password+"\"");
			if (res.next()){
				User user = generateUser(res.getInt("id"));
				sql.closeConnection();
				return user;
			}
			else{
				throw(new IllegalArgumentException("Wrong username or password!"));
			}
		} 
		catch (IllegalArgumentException e){
			throw (e);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private User generateUser(int id){
		try{
			Sql sql = new Sql("jdbc:mysql://localhost/EIST_POLL", "root", "root");
			ResultSet res = sql.executeQuerry("SELECT * FROM Users WHERE id = \""+id+"\" LIMIT 1");
			if(res.next()){
				if(res.getBoolean("prof")){
					return new Lecturer(res.getInt("id"), res.getString("name"), generateArray(res.getString("lectures")));
				}
				else{
					return new Student(res.getInt("id"), res.getString("name"), generateArray(res.getString("lectures")));
				}
			}
			sql.closeConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private Lecture generateLecture(int id){
		try{
			Sql sql = new Sql("jdbc:mysql://localhost/EIST_POLL", "root", "root");
			ResultSet res = sql.executeQuerry("SELECT * FROM Lectures WHERE id =\""+id+"\" LIMIT 1");
			if(!res.next()){
				sql.closeConnection();
				return null;
			}
			Lecture lecture = new Lecture(res.getInt("id"), res.getString("title"), new Lecturer()/*(Lecturer)generateUser(res.getInt("lecturer"))*/);
			System.out.println(lecture.getName());
			sql.closeConnection();
			return lecture;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private List<Lecture> generateLectureList(int[] id){
			List<Lecture> lectures = new LinkedList<Lecture>();
			for(int i = 0; i < id.length; i++){
				lectures.add(generateLecture(id[i]));
			}
			return lectures;
	}
	
	private int[] generateArray(String lectures){
		String[] string = lectures.split(",");
		int[] res = new int[string.length];
		for (int i = 0; i < string.length; i++){
			res[i] = Integer.parseInt(string[i]);
		}
		return res;
	}

	@Override
	public List<Feedback> getFeedback(Lecture lecture) {
		try{
			Sql sql = new Sql("jdbc:mysql://localhost/EIST_POLL", "root", "root");
			ResultSet res = sql.executeQuerry("SELECT * FROM Feedback WHERE lecture = \""+lecture.getId()+"\"");
			List<Feedback> feedbacks = new LinkedList<Feedback>();
			while(res.next()){
				feedbacks.add(new Feedback(res.getInt("id"), generateLecture(res.getInt("lecture")), (Student)generateUser(res.getInt("student")), res.getInt("opinions"), res.getString("like"), res.getString("dislike")));
			}
			sql.closeConnection();
			return feedbacks;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}



	@Override
	public List<Lecture> getLectures(User user) {
		try{
			Sql sql = new Sql("jdbc:mysql://localhost/EIST_POLL", "root", "root");
			ResultSet res = sql.executeQuerry("SELECT lectures FROM Users WHERE id = \""+user.getId()+"\" LIMIT 1");
			if(res.next()){
				String[] ids = res.getString("lectures").split(",");
				int[] id = new int[ids.length];
				for(int i = 0; i < ids.length; i++){
					id[i] = Integer.parseInt(ids[i]);
				}
				sql.closeConnection();
				return generateLectureList(id);
			}
			sql.closeConnection();
			return null;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
